package com.hsy.crm.web.service.asyn.marketprofit;

import com.hsy.crm.web.domain.entity.Message;
import com.hsy.crm.web.domain.entity.StoreProductDetail;
import com.hsy.crm.web.mapper.StoreProductDetailMapper;
import com.hsy.crm.web.utils.ListUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 采购单审核
 */
@Service
public class BuyProfitService {

    @Autowired
    SaleProfitService saleProfitService;

    @Autowired
    StoreProductDetailMapper storeProductDetailMapper;

    public void init(Message message, List<StoreProductDetail> storeProductDetails){
        for (StoreProductDetail storeProductDetail : storeProductDetails){
            this.calcStoreProductDetailDone(message,storeProductDetail);
        }
    }

    public void calcStoreProductDetailDone(Message message,StoreProductDetail storeProductDetail){
        //数据查询  查询最早一次销售未找到库存的明细
        StoreProductDetail unStoreProductDetail = this.selectUnStoreProductDetail(message,storeProductDetail);

        if( unStoreProductDetail == null ){
            return;
        }

        //数据更新  处理未找到库存的销售明细
        unStoreProductDetail.setCustomerId(message.getCustomerId());
        saleProfitService.calcStoreProductDetailDone(message,unStoreProductDetail);

        // 查询所有的销售未找到库存的明细
        List<StoreProductDetail> storeProductDetails = storeProductDetailMapper.selectOutByTime(unStoreProductDetail);
        if(ListUtils.isNotEmpty(storeProductDetails)){
            for ( StoreProductDetail outStoreProductDetail : storeProductDetails ){
                outStoreProductDetail.setCustomerId(message.getCustomerId());
                saleProfitService.calcStoreProductDetailDone(message,outStoreProductDetail);
            }
        }
    }

    private StoreProductDetail selectUnStoreProductDetail(Message message, StoreProductDetail storeProductDetail){
        StoreProductDetail select = new StoreProductDetail();
        select.setCustomerId(message.getCustomerId());
        select.setStoreProductId(storeProductDetail.getStoreProductId());
        select.setBatchNo(storeProductDetail.getBatchNo());
        return storeProductDetailMapper.getUnCalcStoreProductDetail(select);
    }

}
